package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @Author lzc
 * @Date 2022/11/1 14:51
 */
public class Flink03_Function_Agg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("s1", 1L, 10),
            new WaterSensor("s1", 1L, 16),
            new WaterSensor("s1", 1L, 13),
            new WaterSensor("s1", 1L, 11),
            new WaterSensor("s1", 2L, 29)
        );
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(stream);
        tEnv.createTemporaryView("sensor", table);
        
        // 把小字符串变成大写的函数
        // 1. 在 table api 中使用
        // 1.1 内联的方式
       
        // 1.2 先注册再使用
        tEnv.createTemporaryFunction("my_avg", MyAvg.class);
        table
            .groupBy($("id"))
            .select($("id"), call("my_avg", $("vc")).as("vc_avg"))
            .execute()
            .print();
        
        // 2. 在 sql 中
        // 先注册
        tEnv.sqlQuery("select id, my_avg(vc) from sensor group by id").execute().print();
    
    
    }
    
    public static class Avg{
        public Integer sum = 0;
        public Long count= 0L;
    }
    
    public static class MyAvg extends AggregateFunction<Double, Avg> {
    
    
        // 初始化一个累加器
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        
        // 返回的聚和的最终结果
        @Override
        public Double getValue(Avg acc) {
            return acc.sum * 1.0 / acc.count;
        }
        
        // 按照约定定义一个实现聚合过程的方法
        // 第一个参数: 必须是累计器
        // 第二个参数: 参与聚和的那个值
        public void accumulate(Avg acc, Integer vc){
            acc.sum+= vc;
            acc.count++;
        }
        
    
    }
  
}
